package com.matt.repository.impl;

import com.matt.domain.course.Course;
import com.matt.domain.course.CourseChild;
import com.matt.foundation.DO.course.CourseTemplate2DO;
import com.matt.foundation.DO.course.WebCoursePageDO;
import com.matt.foundation.constant.CourseConstant;
import com.matt.foundation.query.ClassesQuery;
import com.matt.foundation.query.CourseAreaQuery;
import com.matt.foundation.query.CourseQuery;
import com.matt.foundation.vo.course.CourseAreaBuildVo;
import com.matt.repository.base.BaseNativeSqlRepository;
import com.matt.repository.base.CourseAllRepository;
import com.matt.repository.course.CourseRepository2;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * *******************************
 * Created by Ron.
 * form com.matt
 * on 2018/1/23
 * *******************************
 */
@Component
public class CourseRepositoryImpl extends BaseNativeSqlRepository implements CourseRepository2 {


    @Override
    public List<Course> courseList(ClassesQuery query) {
        String querySql = String.format("select c.id as id, c.name as name, c.areaId as areaId,c.priority as priority,c.created as created,c.status as status,c.courseCover,c.introduction,c.playCount" +
                " from course c " +
                " WHERE true and c.deleted = 'false' ");

        if (StringUtils.isNotBlank(query.getName())) {
            querySql += String.format(" and c.name  like  concat('%s', '%s', '%s') ", "%", query.getName(), "%");
        }

        if (Objects.nonNull(query.getAreaId())) {
            querySql += String.format(" and c.areaId = '%s' ", query.getAreaId());
        }

        if (Objects.nonNull(query.getType())) {
            querySql += String.format(" and c.type = '%s' ", Integer.valueOf(query.getType()));
        }

        querySql += " order by c.priority asc,c.created desc ";

        querySql += String.format(" limit %s, %s ", query.getPageNum() * query.getPageSize(), query.getPageSize());
        List<Course> objectArrayList = sqlObjectList(querySql, Course.class);
        return objectArrayList;
    }

    @Override
    public Integer courseCount(ClassesQuery query) {
        String querySql = String.format("select count(c.id)" +
                " from course c " +
                " WHERE true and c.deleted = 'false' ");

        if (StringUtils.isNotBlank(query.getName())) {
            querySql += String.format(" and c.name  like  concat('%s', '%s', '%s') ", "%", query.getName(), "%");
        }

        if (Objects.nonNull(query.getAreaId())) {
            querySql += String.format(" and c.areaId = '%s' ", query.getAreaId());
        }

        if (Objects.nonNull(query.getType())) {
            querySql += String.format(" and c.type = '%s' ", Integer.valueOf(query.getType()));
        }

        List objectArrayList = sqlSingleList(querySql);
        return Integer.valueOf(objectArrayList.get(0).toString());
    }


    @Override
    public List<Course> courseLiveList(ClassesQuery query) {
        String querySql = String.format("select c.id as id, c.name as name, c.areaId as areaId,c.priority as priority,c.created as created,c.status as status,c.courseCover,c.introduction,c.videoAddress,c.type,c.playCount" +
                " from course c " +
                " WHERE true and c.deleted = 'false' ");

        if (StringUtils.isNotBlank(query.getName())) {
            querySql += String.format(" and c.name  like  concat('%s', '%s', '%s') ", "%", query.getName(), "%");
        }

        if (Objects.nonNull(query.getAreaId())) {
            querySql += String.format(" and c.areaId = '%s' ", query.getAreaId());
        }

        if (Objects.nonNull(query.getType())) {
            querySql += String.format(" and c.type = '%s' ", Integer.valueOf(query.getType()));
        }else {
            querySql += " and c.type =5 or c.type =6 ";
        }

        querySql += " order by c.priority asc,c.created desc ";

        querySql += String.format(" limit %s, %s ", query.getPageNum() * query.getPageSize(), query.getPageSize());
        List<Course> objectArrayList = sqlObjectList(querySql, Course.class);
        return objectArrayList;
    }

    @Override
    public Integer courseLiveCount(ClassesQuery query) {
        String querySql = String.format("select count(c.id)" +
                " from course c " +
                " WHERE true and c.deleted = 'false' ");

        if (StringUtils.isNotBlank(query.getName())) {
            querySql += String.format(" and c.name  like  concat('%s', '%s', '%s') ", "%", query.getName(), "%");
        }

        if (Objects.nonNull(query.getAreaId())) {
            querySql += String.format(" and c.areaId = '%s' ", query.getAreaId());
        }

        if (Objects.nonNull(query.getType())) {
            querySql += String.format(" and c.type = '%s' ", Integer.valueOf(query.getType()));
        }{
            querySql += " and c.type =5 or c.type =6 ";
        }

        List objectArrayList = sqlSingleList(querySql);
        return Integer.valueOf(objectArrayList.get(0).toString());
    }

    @Override
    public List<CourseChild> findAllChildByAreaIdAndName(CourseAreaQuery query) {
        // 1. 分页参数处理（pageNum从0开始，默认0；pageSize默认10）
        int pageNum = query.getPageNum() == null ? 0 : query.getPageNum();
        int pageSize = query.getPageSize() == null ? 10 : query.getPageSize();
        // 校验参数合法性：pageNum≥0，pageSize≥1
        pageNum = Math.max(pageNum, 0);
        pageSize = Math.max(pageSize, 1);
        int startIndex = pageNum * pageSize; // 从0开始时，起始索引=pageNum×pageSize

        String querySql = String.format("select c.id as id, c.name as name,c.videoAddress as videoAddress,c.created as created,c.status as status,c.videoImg,c.courseId,c.parentId,c.type,c.ancestorsId,c.priority" +
                " from course_child c " +
                " WHERE c.deleted = 'false' ");

        if (StringUtils.isNotBlank(query.getName())) {
            querySql += String.format(" and c.name like concat('%%', '%s', '%%') ", query.getName());
        }
        if (Objects.nonNull(query.getCourseId())) {
            querySql += String.format(" and c.courseId = '%s' ", query.getCourseId());
        }

        // 2. 继续保留：courseIds空指针防护 + in条件语法修复
        if (Objects.nonNull(query.getCourseIds()) && !query.getCourseIds().isEmpty()) {
            // 遍历集合，给每个ID加上单引号，再用逗号拼接
            String courseIdsStr = query.getCourseIds().stream()
                    .map(id -> "'" + id + "'") // 关键：给每个字符串ID加单引号
                    .collect(Collectors.joining(","));
            querySql += String.format(" and c.courseId in (%s) ", courseIdsStr);
        }

        querySql += " order by c.priority asc,c.created desc ";
        // 3. 分页参数：使用从0开始计算的startIndex
        querySql += String.format(" limit %s, %s ", startIndex, pageSize);

        List<CourseChild> objectArrayList = sqlObjectList(querySql, CourseChild.class);
        return objectArrayList == null ? new ArrayList<>() : objectArrayList;
    }

    @Override
    public Integer findAllChildCounts(CourseAreaQuery query) {
        String querySql = String.format("select count(c.id)" +
                " from course_child c " +
                " WHERE c.deleted = 'false' ");

        if (StringUtils.isNotBlank(query.getName())) {
            querySql += String.format(" and c.name like concat('%%', '%s', '%%') ", query.getName());
        }

        if (Objects.nonNull(query.getCourseId())) {
            querySql += String.format(" and c.courseId = '%s' ", query.getCourseId());
        }

        // 2. 继续保留：courseIds空指针防护 + in条件语法修复
        if (Objects.nonNull(query.getCourseIds()) && !query.getCourseIds().isEmpty()) {
            // 遍历集合，给每个ID加上单引号，再用逗号拼接
            String courseIdsStr = query.getCourseIds().stream()
                    .map(id -> "'" + id + "'") // 关键：给每个字符串ID加单引号
                    .collect(Collectors.joining(","));
            querySql += String.format(" and c.courseId in (%s) ", courseIdsStr);
        }

        List<Object> objectArrayList = sqlSingleList(querySql);
        // 修复：空值防护，避免索引异常
        if (objectArrayList == null || objectArrayList.isEmpty() || objectArrayList.get(0) == null) {
            return 0;
        }
        // 安全转换为Integer（兼容数据库返回的BigDecimal/Long）
        return Integer.parseInt(objectArrayList.get(0).toString());
    }
}
